package cn.xfdtool.slowsql.listener.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.xfdtool.slowsql.dto.SlowSQLNotifyDTO;
import cn.xfdtool.slowsql.listener.SlowSQLNotifyListener;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

/**
 * 日志监听器
 *
 * @author xfd
 * 2022/5/14
 */
@Slf4j
public class LogSlowSQLNotifyListener implements SlowSQLNotifyListener {

    @Override
    public void notify(SlowSQLNotifyDTO slowSQLNotifyDTO) {
        if (!slowSQLNotifyDTO.isParseSuccess()) {
            StringBuilder logMsg = new StringBuilder();
            logMsg.append("解析SQL数据异常, ")
                    .append("方法[").append(slowSQLNotifyDTO.getMethodName()).append("], ")
                    .append("预编译SQL[").append(slowSQLNotifyDTO.getPrepareSQL()).append("], ")
                    .append("参数[").append(ObjectUtil.isNull(slowSQLNotifyDTO.getArgs()) ? "" : JSON.toJSONString(slowSQLNotifyDTO.getArgs())).append("], ")
                    .append("业务异常[").append(ObjectUtil.isEmpty(slowSQLNotifyDTO.getThrowable()) ? "" : ExceptionUtil.getRootCause(slowSQLNotifyDTO.getThrowable())).append("], ")
                    .append("解析异常[").append(ObjectUtil.isEmpty(slowSQLNotifyDTO.getParseError()) ? "" : ExceptionUtil.getRootCause(slowSQLNotifyDTO.getParseError())).append("].")
            ;
            log.error(logMsg.toString());
            return;
        }
        // 构建数据
        StringBuilder logMsg = buildLogMsg(slowSQLNotifyDTO);
        log.error(logMsg.toString());
    }

    /**
     * 构建日志
     * @param slowSQLNotifyDTO
     * @return
     */
    protected StringBuilder buildLogMsg(SlowSQLNotifyDTO slowSQLNotifyDTO) {
        StringBuilder logMsg = new StringBuilder();
        // 构建数据
        logMsg.append(ObjectUtil.isEmpty(slowSQLNotifyDTO.getThrowable()) ? "大SQL, " : "慢SQL, ")
                .append("耗时[").append(slowSQLNotifyDTO.getExecTime()).append("]毫秒, ")
                .append("结果条数[").append(slowSQLNotifyDTO.getResultRowCount()).append("], ")
                .append("方法[").append(slowSQLNotifyDTO.getMethodName()).append("], ")
                .append("预编译SQL[").append(slowSQLNotifyDTO.getPrepareSQL()).append("], ")
                .append("执行SQL[").append(ObjectUtil.isEmpty(slowSQLNotifyDTO.getExecSQL()) ? "" : slowSQLNotifyDTO.getExecSQL()).append("], ")
                .append("参数[").append(ObjectUtil.isNull(slowSQLNotifyDTO.getArgs()) ? "" : JSON.toJSONString(slowSQLNotifyDTO.getArgs())).append("], ")
                .append("业务异常[").append(ObjectUtil.isEmpty(slowSQLNotifyDTO.getThrowable()) ? "" : ExceptionUtil.getRootCause(slowSQLNotifyDTO.getThrowable())).append("].")
        ;
        return logMsg;
    }
}
